package ferp.android.views.table.controller;

import android.graphics.Point;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import ferp.android.views.CardView;
import ferp.android.views.table.TableView;
import ferp.android.views.table.animation.MovingCard;
import ferp.core.game.Game;
import ferp.core.player.Player;

/**
* User: olegs
* Date: 05/01/2015 11:59
*/
public class CardDoubleTapController extends MovingController
{
  public CardDoubleTapController(TableView.Listener listener, TableView table, MovingCard mc, Rect sink)
  {
    super(listener, table, mc, sink);
  }

  @Override
  public void select(int player, CardView cv)
  {
    selected[player] = cv;
    super.select(player, cv);
  }

  @Override
  public void deselect(int player, CardView cv)
  {
    super.deselect(player, cv);
    selected[player] = null;
  }

  @Override
  public void onMovingStarted(int player, CardView cv, Point touch)
  {
    CardView previous = selected[player];

    // move previously selected card view back to the player's hand
    if (previous != null)
      deselect(player, previous);

    // elevate/shift newly selected card view
    if (previous != cv)
    {
      select(player, cv);

      // initialize moving card state
      mc.initialize(cv, touch);
    }
  }

  @Override
  public int elevation(int player, CardView cv) {return isSelected(player, cv) && Player.isHuman(player) ? -OFFSET : 0;}

  @Override
  public int shift(int player, CardView cv)
  {
    if (!isSelected(player, cv) || Player.isHuman(player))
      return 0;

    return player == Game.next(game().human().id()) ? OFFSET : -OFFSET;
  }

  @Override
  public void onTouch(View view, MotionEvent motionEvent)
  {
    Game g = game();
    CardView cv = selected[g.player.current];

    if (cv == null)
      super.onTouch(view, motionEvent);
    else
      if (state == State.NONE && sink.contains((int)motionEvent.getX(), (int)motionEvent.getY()))
      {
        // move controller to 'ANIMATION' state to prevent offer dialog appearance and as consequence double processing
        state = State.ANIMATION;

        // disable player's card to prevent card moving during animation
        table.enablePlayerCards(g.player.current, false);

        // animate the card view to trick area
        listener.onCardReleased(cv.card());
      }
  }

  private boolean isSelected(int player, CardView cv) {return selected[player] == cv;}
}
